/*
 * (C) Copyright 2006-2010 Nuxeo SAS (http://nuxeo.com/) and contributors.
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Lesser General Public License
 * (LGPL) version 2.1 which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/lgpl.html
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * Lesser General Public License for more details.
 *
 * Contributors:
 *     bstefanescu
 */
package org.nuxeo.gwt.habyt.app.client;

import java.util.HashMap;
import java.util.Map;

import org.nuxeo.gwt.habyt.app.client.form.FormWidget;
import org.nuxeo.gwt.habyt.templates.client.TemplatePanel;
import org.nuxeo.gwt.habyt.templates.client.bindings.Helper;

import com.google.gwt.dom.client.Element;
import com.google.gwt.user.client.ui.Widget;

/**
 * @author <a href="mailto:bs@nuxeo.com">Bogdan Stefanescu</a>
 * 
 */
public class Application {

    private static Application instance;

    public static void set(Application instance) {
        Application.instance = instance;
    }

    public static Application get() {
        if (instance == null) {
            instance = new Application();
        }
        return instance;
    }

    /**
     * Active views
     */
    protected Map<String, View> views;

    public Application() {
        views = new HashMap<String, View>();
    }

    public void showMessage(String msg) {
        MessagePopup w = new MessagePopup(msg);
        w.show();
    }

    public Action<?> getAction(String expr) {
        int i = expr.indexOf(':');
        if (i == -1) {
            return ActionFactory.get().getAction(expr);
        }
        Action<?> action = ActionFactory.get().getAction(expr.substring(0, i));
        action.loadData(expr.substring(i + 1));
        return action;
    }

    public View getView(String id) {
        return views.get(id);
    }

    public void addView(View view) {
        views.put(view.getId(), view);
    }

    public void removeView(View view) {
        views.remove(view.getId());
    }

    public BusyIndicator getBusy(Widget target) {
        return new BusyIndicator(target);
    }

    public static FormWidget getForm(Element element) {
        Element p = element.getParentElement();
        while (p != null) {
            Widget w = Helper.getWidget(p);
            if (w instanceof FormWidget) {
                return (FormWidget) w;
            }
            p = p.getParentElement();
        }
        return null;
    }

    public static Widget findWidget(String id) {
        return TemplatePanel.findWidget(id);
    }

}
